package com.spark.sniffer.plugin.plugins.interceptor;

import java.lang.reflect.Method;

import com.spark.sniffer.AgentArgs;
import com.spark.sniffer.plugin.interceptor.enhance.InstanceMethodsAroundInterceptor;
import com.spark.sniffer.plugin.interceptor.enhance.MethodInterceptResult;
import com.spark.sniffer.tracing.Span;
import com.spark.sniffer.tracing.TracingContext;

public class EhcacheTemplateInterceptor implements InstanceMethodsAroundInterceptor {

    @Override
    public void beforeMethod(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        MethodInterceptResult result) throws Throwable {
        TracingContext.getContext().startSpan(Span.Type.EhCache,
            method.getName() + (AgentArgs.isSimpleTracing() ? "" : ("<" + allArguments[1] + ">")));
    }

    @Override
    public Object afterMethod(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        Object ret) throws Throwable {
        TracingContext.getContext().stopSpan();
        return ret;
    }

    @Override
    public void handleMethodException(Object instance, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
        Throwable t) {
        TracingContext.getContext().setActiveSpanCode(Span.ERR_CODE);
    }
}
